//
//  MindBodyConnection.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/9.
//

import UIKit
import ProgressHUD
import SwiftyStoreKit
import StoreKit


class MindBodyConnection: UIViewController {
    var recordpageOneXuHTL:Int = 0
    
    var mindfulness:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?
    var eachVioViewHTLC:THLCNOrBUTTOn?
    var mindfulnessPageHTL:THLCNPageControll?
    var journeyHTLC:UIView?
    let pauyingHTL_OVd:(Array<(String,Int,String)>,Int) = ([("geetfricjdhhnfje",400,HTLROOOMMeasg.BinrwetioBase64("JDAuOTk=")),
                     ("qtxlctnuuxhydkjc",800,HTLROOOMMeasg.BinrwetioBase64("JDEuOTk=")),
                     ("ddgdjqidvsyqfweg",2450,HTLROOOMMeasg.BinrwetioBase64("JDQuOTk=")),
                        ("uvgquijboundesfiop",3550,HTLROOOMMeasg.BinrwetioBase64("JDYuOTk=")),
                     ("kfpmtaoepzphrxih",4900,HTLROOOMMeasg.BinrwetioBase64("JDkuOTk=")),
                     ("litndihgozzqgzod",9800,HTLROOOMMeasg.BinrwetioBase64("JDE5Ljk5")),
                       ("uvgundesfiopsloow",14550,HTLROOOMMeasg.BinrwetioBase64("JDI5Ljk5")),
                     ("zrczukezgynylteb",24500,HTLROOOMMeasg.BinrwetioBase64("JDQ5Ljk5")),
                       ("uvgeundesfiophoyi",38550,HTLROOOMMeasg.BinrwetioBase64("JDc5Ljk5")),
                                                            ("suoxgoojjvrdmtnq",49000,HTLROOOMMeasg.BinrwetioBase64("JDk5Ljk5"))],100)
    
    
    @IBOutlet weak var htklBg: UIView!
    
    @IBOutlet weak var iijopil: UILabel!
    
    @IBAction func Funrightnoweback(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        htklBg.layer.cornerRadius = 20
        htklBg.layer.masksToBounds  = true
        
        mindfulness = [99]
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]
        
      
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let customized = "1customized0".components(separatedBy: "customized")
        
        
        let banlanceHTLC =  Int(HTLCAllDealRelaxing.Relaxing.signinUserDataHTL["HTLCcoin"] ?? customized[1]) ?? 0
        self.mineBlanceHTL.text = "\(banlanceHTLC)"
        let coijfLayout = UICollectionViewFlowLayout.init()
        coijfLayout.itemSize = CGSize.init(width: (UIScreen.main.bounds.width - 36)/2, height:150)
        
        coijfLayout.minimumInteritemSpacing = 12
        coijfLayout.scrollDirection = .vertical
        coijfLayout.minimumLineSpacing = 14
        
        minaertHTLC = UICollectionView.init(frame: .zero, collectionViewLayout: coijfLayout)
        
        let nib = UINib(nibName: "AromatherapySession", bundle: nil)
               
        minaertHTLC?.register(nib, forCellWithReuseIdentifier: "HTLCoinlIotemID")
             
        minaertHTLC?.delegate = self
        minaertHTLC?.dataSource = self
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }

        mindfulnessPageHTL = THLCNPageControll()
        mindfulnessPageHTL?.numberOfPages = 1
        mindfulnessPageHTL?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.tintColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.sizeToFit()

        if journeyHTLC != nil {
            journeyHTLC?.addSubview(mindfulnessPageHTL ?? THLCNPageControll.init())
           
        }
        minaertHTLC?.showsVerticalScrollIndicator = false
        minaertHTLC?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 310, right: 0)
        minaertHTLC?.showsVerticalScrollIndicator = false
       
        minaertHTLC?.backgroundColor = .clear
        minaertHTLC?.selectItem(at: IndexPath.init(row: 0, section: 0), animated: false, scrollPosition: .top)
       
        view.insertSubview(minaertHTLC!, belowSubview: sureAkiio)
        minaertHTLC?.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(12)
            make.bottom.equalToSuperview()
            make.top.equalTo(iijopil.snp.bottom).offset(23)
        }
      
        
    }
    
    @IBOutlet weak var sureAkiio: UIButton!
    
    @IBOutlet weak var mineBlanceHTL: UILabel!

    var minaertHTLC: UICollectionView?
    
    
    
    
    @IBAction func rightNowertPayHTLC(_ sender: Any) {
        
        self.view.isUserInteractionEnabled = false
        ProgressHUD.animate(HTLROOOMMeasg.BinrwetioBase64("aXMgUGF5aW5nLi4uLi4u"))
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }
        purchaseProductAndUpdateBalance() 
//        SwiftyStoreKit.purchaseProduct(pauyingHTL_OVd.0[recordpageOneXuHTL].0, atomically: true) { psResult in
//             
//            self.view.isUserInteractionEnabled = true
//            ProgressHUD.dismiss()
//            
//            
//            if case .success(let psPurch) = psResult {
//               
//               
//                let psdownloads = psPurch.transaction.downloads
//                if !psdownloads.isEmpty {
//                    SwiftyStoreKit.start(psdownloads)
//                }
//                
//                if psPurch.needsFinishTransaction {
//                    SwiftyStoreKit.finishTransaction(psPurch.transaction)
//                }
//            
//                let customized = "1customized0".components(separatedBy: "customized")
//                
//                var banlanceHTLC =  Int(HTLCAllDealRelaxing.Relaxing.signinUserDataHTL["HTLCcoin"] ?? customized[1]) ?? 0
//                
//               
//                    banlanceHTLC = banlanceHTLC + self.pauyingHTL_OVd.0[self.recordpageOneXuHTL].1
//                    
//                    HTLCAllDealRelaxing.Relaxing.signinUserDataHTL["HTLCcoin"]  = "\(banlanceHTLC)"
//                    
//                    self.mineBlanceHTL.text = "\(banlanceHTLC)"
//               
//               
//                ProgressHUD.succeed(HTLROOOMMeasg.BinrwetioBase64("U3VjY2Vzc2Z1bCBwYXltZW50ISEh"), delay: 2.0)
//              
//          
//            }else if case .error(let error) = psResult {
//               
//               
//                if error.code == .paymentCancelled {
//                    return
//                }
//                ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), error.localizedDescription, delay: 2.0)
//                
//               
//            }
//        }

    }
    
    
    func purchaseProductAndUpdateBalance() {
        SwiftyStoreKit.purchaseProduct(pauyingHTL_OVd.0[recordpageOneXuHTL].0, atomically: true) { psResult in
            self.handlePurchaseResult(psResult)
        }
    }

    private func handlePurchaseResult(_ psResult: PurchaseResult) {
        self.view.isUserInteractionEnabled = true
        ProgressHUD.dismiss()
        
        switch psResult {
        case .success(let psPurch):
            handlePurchaseSuccess(psPurch)
        case .error(let error):
            handlePurchaseError(error)
        }
    }

    private func handlePurchaseSuccess(_ psPurch: PurchaseDetails) {
        let psdownloads = psPurch.transaction.downloads
        if !psdownloads.isEmpty {
            SwiftyStoreKit.start(psdownloads)
        }

        if psPurch.needsFinishTransaction {
            SwiftyStoreKit.finishTransaction(psPurch.transaction)
        }

        updateUserBalance()
        showSuccessHUD()
    }

    private func handlePurchaseError(_ error: SKError) {
        if error.code == .paymentCancelled {
            return
        }
        ProgressHUD.banner(
            HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),
            error.localizedDescription,
            delay: 2.0
        )
    }

    private func updateUserBalance() {
        let customized = "1customized0".components(separatedBy: "customized")
        let fallbackCoin = "1X0fallback".components(separatedBy: "X")[1]
        
        var balanceHTL = Int(
            HTLCAllDealRelaxing.Relaxing.signinUserDataHTL["HTLCcoin"]
            ?? customized.last
            ?? fallbackCoin
        ) ?? 0
        
        balanceHTL += self.pauyingHTL_OVd.0[self.recordpageOneXuHTL].1
        HTLCAllDealRelaxing.Relaxing.signinUserDataHTL["HTLCcoin"] = "\(balanceHTL)"
        self.mineBlanceHTL.text = "\(balanceHTL)"
    }

    private func showSuccessHUD() {
        let randomFactor = Int.random(in: 1...9)
        if randomFactor % 2 == 0 {
            ProgressHUD.succeed(HTLROOOMMeasg.BinrwetioBase64("U3VjY2Vzc2Z1bCBwYXltZW50ISEh"), delay: 2.0)
        } else {
            ProgressHUD.succeed(HTLROOOMMeasg.BinrwetioBase64("U3VjY2Vzc2Z1bCBwYXltZW50ISEh"), delay: 2.0)
          
        }
    }

}


extension MindBodyConnection:UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      
        return pauyingHTL_OVd.0.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     
        let lkioCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HTLCoinlIotemID", for: indexPath) as! AromatherapySession
       
       
            lkioCell.payworthTHLC.text = pauyingHTL_OVd.0[indexPath.row].2
            lkioCell.noqingCountLbl.text =  "\(pauyingHTL_OVd.0[indexPath.row].1)"
      
      
        return lkioCell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      
      
            self.recordpageOneXuHTL = indexPath.row
        
        
    }
    
    
}
